package top.szhome.framework.starter.template.engine;

import lombok.extern.slf4j.Slf4j;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;

import java.io.IOException;
import java.util.Map;

/**
 * Beetl模板引擎
 *
 * @author 唐加利
 * @date 2023/7/14
 **/
@Slf4j
public class BeetlEngine implements TemplateEngine {

    private GroupTemplate template;

    /**
     * 构造模板引擎
     */
    public BeetlEngine() {
        StringTemplateResourceLoader loader = new StringTemplateResourceLoader();
        Configuration configuration = null;
        try {
            configuration = Configuration.defaultConfiguration();
        } catch (IOException e) {
            configuration = null;
        }
        this.template = new GroupTemplate(loader, configuration);
    }

    @Override
    public String process(String name, String template, Map<String, Object> context) {
        try {
            Template temp = this.template.getTemplate(template);
            temp.binding(context);
            return temp.render();
        } catch (Exception e) {
            log.error("模板解析异常，name={}, template={}", name, template, e);
            return null;
        }
    }

}
